import { Controller } from "egg";
import { mapKeys, camelCase } from "lodash";
/*const appSearchParamRule = {
  appID: { required: false, type: "string" },
  appName: { required: false, type: "string" },
  orgID: { required: false, type: "number" },
  page: { type: "number", defaultValue: 1, convertType: true }
};*/
const singleAppSearchParamRule = {
  appID: { type: "string" }
};
const appCreateParamRule = {
  appName: { type: "string" },
  code: { type: "string" },
  remark: { required: false, type: "string" }
};

export default class AppController extends Controller {
  public async list(ctx) {
    // const { page } = ctx.request.body;
    const page = 1;
    // 参数校验失败自动返回422状态
    // ctx.validate(appSearchParamRule);
    // ctx.response.status = 404;
    const { count, rows: list } = await ctx.model.App.findAndCountAll({
      include: [{ attributes: [], model: ctx.model.Version, required: false }],
      attributes: [
        ["id", "appId"],
        ["app_name", "appName"],
        [ctx.model.col("Versions.platform"), "platform"],
        ["org_id", "orgId"],
        ["apk", "apk"],
        ["create_time", "createTime"],
        ["modify_time", "modifyTime"]
      ],
      offset: (page - 1) * 10,
      limit: 10,
      subQuery: false
    });
    ctx.body = {
      success: true,
      data: {
        count,
        list
      }
    };
  }

  public async findAll(ctx) {
    // const { page } = ctx.request.body;
    const page = 1;
    // 参数校验失败自动返回422状态
    // ctx.validate(appSearchParamRule);
    // ctx.response.status = 404;
    const rows = await ctx.model.App.findAll({
      include: [{ attributes: [], model: ctx.model.Version, required: false }],
      attributes: [
        ["id", "appId"],
        ["app_name", "appName"],
        [ctx.model.col("Versions.platform"), "platform"],
        ["org_id", "orgId"],
        ["apk", "apk"],
        ["create_time", "createTime"],
        ["modify_time", "modifyTime"]
      ],
      subQuery: false
    });
    ctx.body = {
      success: true,
      list: rows.map(r =>
        mapKeys(r.get(), (_v, k) => {
          return camelCase(k);
        })
      )
    };
  }

  public async fetchOne(ctx) {
    // const { page } = ctx.request.body;
    ctx.validate(singleAppSearchParamRule);
    ctx.body = {};
  }

  public async create(ctx) {
    ctx.validate(appCreateParamRule);
    ctx.body = {};
  }

  public async delete(ctx) {
    ctx.body = {};
  }

  public async update(ctx) {
    ctx.validate(appCreateParamRule);
    ctx.body = {};
  }
}
